<?php
namespace Com\Pay;
class TuBeiPay{

    private $config = array();


    public function __construct($send_data){
        $this->config = $send_data;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $price = $order_info['paymoney'];
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/NotifyCallback/TuBeiPayNotify';
        $order_sn = $order_info['ordernumber'];
        if('/' == DIRECTORY_SEPARATOR){
            $server_ip = $_SERVER['SERVER_ADDR'];
        }else{
            $server_ip =@gethostbyname($_SERVER['SERVER_NAME']);
        }
        $post_data = array(
            "mch_id"  =>  $this->config['mch_id'],
            'nonce_str' => substr(md5(mt_rand(1010101 , 9182635)) , 20),
            'body' => 'CBpay',
            'out_trade_no' => $order_sn,
            'total_fee' => $price * 100,
            'spbill_create_ip' => $server_ip,
            'notify_url' => $notifyUrl,
            'return_url' => $order_info['return_url'],
            'trade_type' => $order_info['payType'],
        );
        $ContentSign = $this->setParam($post_data,$this->config['mch_key'],false); // 计算出Sign
        $post_data['sign'] = $ContentSign; // Sign签名
        $tar_url = "https://api.tubeipay.com/v1/pay/unifiedorder";
        $bw = $this->arrayToXml($post_data);
        $header[] = "Content-type: text/xml";      //定义content-type为xml,注意是数组
        $ch = curl_init ($tar_url);
        curl_setopt($ch, CURLOPT_URL, $tar_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $bw);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
           print_r(curl_error($ch));
           exit;
        }
        curl_close($ch);
        $res = xmlToArray($response);
        if($res['result_code'] == "SUCCESS"){
            return $res['prepay_url'];
        }
        return '';
    }

    //数组转XML
    private function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    private function setParam($param,$key,$IS_Notify){
        unset($param['PHPSESSID']);
        ksort($param);
        $str = "";
        foreach ($param as $k => $v){
            if($IS_Notify && $k == 'sign') continue;
            $str.= $k . '=' . $v . '&';
        }
        $str1 = rtrim($str , '&');
        $sign = strtoupper(md5($str1  . '&key=' . $key));
        return $sign;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $datas = xmlToArray(file_get_contents('php://input'));
        $MySign = $this->setParam($datas,$this->config['mch_key'],true);
        if($datas['sign'] == $MySign){
            if($datas['return_code'] == 'SUCCESS'){
                return true;
            }else{
                // 失败
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }


}
